package utils;

import book.PairOfUidAndBookId;
import com.bit.utils.FileUtils;

import java.io.IOException;

public class AnalyzingBorrowedBook {
    public void storeObject(PairOfUidAndBookId[] pairOfUidAndBookIds, String filename) throws IOException {
        int bookUselen = 0;
        for (int i = 0; i < pairOfUidAndBookIds.length; i++) {
            if (pairOfUidAndBookIds[i] != null) {
                bookUselen++;
            }
        }
        StringBuilder jsonArray = new StringBuilder();
        for (int i = 0; i < bookUselen; i++) {
            if (pairOfUidAndBookIds[i] != null) {
                jsonArray.append(pairOfUidAndBookIds[i].toJson());
                if (i != bookUselen - 1) {
                    jsonArray.append("\n");
                }
            }
        }
        FileUtils.writeFile(jsonArray.toString(), filename);
    }

    public PairOfUidAndBookId[] loadObject(String filename) throws IOException{
        String content = FileUtils.readFile(filename);
        if (content == null || content.isEmpty()) {
            System.out.println("已借阅书籍列表无数据，没有用户借阅过书籍");
            return null;
        }
        String[] JsonStrings = content.split("\n");
        PairOfUidAndBookId[] borrowedBookList = new PairOfUidAndBookId[JsonStrings.length];
        for (int i = 0; i < JsonStrings.length; i++) {
            PairOfUidAndBookId pairOfUidAndBookId = new PairOfUidAndBookId();
            String[] ret = JsonStrings[i].split(",");
            pairOfUidAndBookId.setUserId(Integer.parseInt(ret[0]));
            pairOfUidAndBookId.setBookId(Integer.parseInt(ret[1]));
            borrowedBookList[i] = pairOfUidAndBookId;
        }
        return borrowedBookList;
    }

}
